package reports.directors;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import coreModel.HIT;
import coreModel.Product;
import coreModel.ProductGroup;
import coreModel.StorageUnit;
import coreModel.StorageUnitManager;
import reports.builders.IBuilder;

public class ProductStatisticsReport implements IDirector {

	
	private int months;

	public ProductStatisticsReport(int nMonths)
	{
		this.months = nMonths;
	}
	
	@Override
	public void build(IBuilder builder)
	{
		if (months <= 0)
			throw new RuntimeException("Hey, you have to set the number " +
												"of months to run this report!");
		
		builder.addTitle("Product Report (" + months + " Months)");
		
		
		
		ArrayList<String> headers = new ArrayList<String>();
		headers.add("Description");
		headers.add("Barcode");
		headers.add("Size");
		headers.add("3-Month Supply");
		headers.add("Supply: Cur/Avg");
		headers.add("Supply: Min/Max");
		headers.add("Supply: Used/Added");
		headers.add("Shelf Life");
		headers.add("Used Age: Avg/Max");
		headers.add("Cur Age: Avg/Max");
		//added for pdf Builder
		builder.startTable(headers.size());
		
		builder.addTableHeader(headers);
		
		Collection <Product> allProducts = 
			new ArrayList<Product>(HIT.getInstance().getProductManager().getAllProducts());
		Collections.sort((List<Product>)allProducts);
		
		for (Product p : allProducts)
		{
			builder.addRow( getRow(p) );
		}
		
		builder.endTable();
		
		builder.saveToFile();
		
	}
	
	private Collection<String> getRow(Product p)
	{
		ArrayList<String> row = new ArrayList<String>();
		
		ProductStatsGenerator stats = new ProductStatsGenerator(p, months);
		
		DecimalFormat oneDec = new DecimalFormat("#.#");
		
		row.add(p.getDescription());
		row.add(p.getBarcode().toString());
		row.add(p.getSupply().toString());
		row.add("" + ( (p.getThreeMonthSupply() == 0)? "" : p.getThreeMonthSupply()) );
		row.add(stats.getCurSupply() + " / " + oneDec.format(stats.getAvgSupply()) );
		row.add(stats.getMinSupply() + " / " + stats.getMaxSupply());
		row.add(stats.getUsedSupply() + " / " + stats.getAddedSupply());
		row.add("" + ( (p.getShelfLife() == 0)? "" : (p.getShelfLife() + " months") ) );
		row.add(oneDec.format(stats.getAvgUsedAge())+" days / " + stats.getMaxUsedAge()+" days");
		row.add(oneDec.format(stats.getAvgCurAge()) + " days / " + stats.getMaxCurAge()+ " days");
		
		return row;
	}
	
	
}
